6  Basic R Syntax - Practical

6.1 Introduction

The pre-class reading for this section covered a number of topics, which we’ll revise today:

  • Variables and Assignment

  • Data Types in R

  • Vectors and Vector Operations

6.2 Variables and Assignment

Demonstration

We can create variables, operate on variables, and update variables.

Create:

greeting <- "hello world"  # assigns the value 'hello world' to variable [greeting]
print(greeting)            # print the value of [greeting] to the console
[1] "hello world"

Operate:

x <- 10
y <- 5
sum <- x + y # adds the values of each variable
print(sum)
[1] 15

Update:

turn <- 0        # set [turn] to zero
turn <- turn + 1 # increment [turn] by 1
print(turn)      # print updated value of 'turn'
[1] 1

Practice

Assigning Values to Variables

Objective: Learn how to assign a value to a variable.

  • Assign the value 10 to a variable named [x].
  • Assign the value 25 to a variable named [y].
  • Print the values of [x] and [y] using the print() function.
Show solution
x <- 10
y <- 25

print(x)  # Should output: [1] 10
print(y)  # Should output: [1] 25

Performing Basic Arithmetic Operations

Objective: Understand how to use variables in arithmetic operations.

  • Create a variable [a] and assign it the value 5.
  • Create a variable [b] and assign it the value 3.
  • Create a new variable [sum_result] that stores the sum of [a] and [b].
  • Create another variable [product_result] that stores the product of [a] and [b].
  • Print the values of [sum_result] and [product_result].
Show solution
a <- 5
b <- 3

sum_result <- a + b
product_result <- a * b

print(sum_result)  # Should output: [1] 8
print(product_result)  # Should output: [1] 15

Updating Variable Values

Objective: Learn how to update the value of a variable.

  • Assign the value 50 to a variable named [total].

  • Increase the value of [total] by 20 using the <- operator.

  • Decrease the value of [total] by 10.

  • Print the updated value of [total].

Show solution
total <- 50
total <- total + 20
total <- total - 10

print(total)  # Should output: [1] 60

Using Variables in a Formula

Objective: Practice using variables in a more complex expression.

  • Assign the value 4 to a variable named [length].
  • Assign the value 6 to a variable named [width].
  • Calculate the area of a rectangle using the formula [area] = [length] * [width].
  • Calculate the perimeter of the rectangle using the formula [perimeter] = 2 * ([length] + [width]).
  • Print the values of [area] and [perimeter].
Show solution
length <- 4
width <- 6

area <- length * width
perimeter <- 2 * (length + width)

print(area)  # Should output: [1] 24
print(perimeter)  # Should output: [1] 20

Swapping Variable Values

Objective: Understand how to manipulate and swap variable values.

  • Assign the value 7 to a variable named [m].
  • Assign the value 14 to a variable named [n].
  • Swap the values of [m] and [n] using a temporary variable.
  • Print the values of [m] and [n] after the swap.
Show solution
m <- 7
n <- 14

# Swapping values
temp <- m
m <- n
n <- temp

print(m)  # Should output: [1] 14
print(n)  # Should output: [1] 7

6.3 Data Types in R

Practice

Identifying Data Types

Objective: Learn to identify and understand different data types.

  • Create a variable [num] and assign it the value 42. Check the data type of [num] using the class() function.
  • Create a variable [name] and assign it the value “John Doe”. Check the data type of [name].
  • Create a variable [is_raining] and assign it the value TRUE. Check the data type of [is_raining].
Show solution
num <- 42
class(num)  # Should output: [1] "numeric"

name <- "John Doe"
class(name)  # Should output: [1] "character"

is_raining <- TRUE
class(is_raining)  # Should output: [1] "logical"

Converting Between Data Types

Objective: Practice converting data between different types.

  • Create a variable [a] and assign it the numeric value 5.
  • Convert [a] to a character type and assign it to a new variable [a_char].
  • Convert [a_char] back to a numeric type and assign it to a variable [a_num].
  • Print the values and types of [a_char] and [a_num].
Show solution
a <- 5
a_char <- as.character(a)
a_num <- as.numeric(a_char)

print(a_char)  # Should output: [1] "5"
print(class(a_char))  # Should output: [1] "character"

print(a_num)  # Should output: [1] 5
print(class(a_num))  # Should output: [1] "numeric"

Working with Logical Values

Objective: Understand how logical values work in R.

  • Create a variable [x] and assign it the value 10.
  • Create a variable [y] and assign it the value 15.
  • Create a logical variable [is_greater] that checks if x is greater than y.
  • Create another logical variable [is_equal] that checks if x is equal to y.
  • Print the values of [is_greater] and [is_equal].
Show solution
x <- 10
y <- 15

is_greater <- x > y
is_equal <- x == y

print(is_greater)  # Should output: [1] FALSE
print(is_equal)  # Should output: [1] FALSE

Creating and Using Factors

Objective: Get familiar with the factor data type, often used for categorical data.

  • Create a character vector [colours] with the values “red”, “blue”, “green”, “blue”, “red”.
  • Convert colours to a factor and assign it to a variable [colour_factor].
  • Print [colour_factor] and check its data type using class().
  • Use the levels() function to display the levels of [colour_factor].
Show solution
colours <- c("red", "blue", "green", "blue", "red")
colour_factor <- factor(colours)

print(colour_factor)  
# Should output:
# [1] red   blue  green blue  red  
# Levels: blue green red

print(class(colour_factor))  # Should output: [1] "factor"

print(levels(colour_factor))  # Should output: [1] "blue"  "green" "red"

Combining Different Data Types in a Vector

Objective: Explore how combining different data types in a vector results in coercion to a single data type.

  • Create a vector [mixed] with the elements 5, “hello”, and TRUE.
  • Print [mixed] and check its data type using class().
  • Try to perform a numeric operation on [mixed], such as adding 2 to it, and observe what happens.
Show solution
mixed <- c(5, "hello", TRUE)

print(mixed)  
# Should output: [1] "5"     "hello" "TRUE"
print(class(mixed))  # Should output: [1] "character"

# Try a numeric operation

# mixed_numeric <- mixed + 2 ### Note this line should be run, but has to be commented as it returns an error

# This will result in an error because the vector is of character type.

Checking Lengths of Vectors

Objective: Understand how to check the length of vectors and why it’s important.

  • Create a numeric vector [numbers] with the values 10, 20, 30, 40, 50.
  • Create a character vector [letters] with the values “a”, “b”, “c”.
  • Use the length() function to check the length of both vectors.
  • Print the lengths of [numbers] and [letters].
Show solution
numbers <- c(10, 20, 30, 40, 50)
letters <- c("a", "b", "c")

print(length(numbers))  # Should output: [1] 5
print(length(letters))  # Should output: [1] 3

6.4 Vectors and Vector Operations

Practice

These tasks will help you implement some of the techniques discussed earlier in the tutorial.

Try to complete these tasks without looking at the solutions!

Create a vector

Write an R script to create a vector named [player_id] that contains the integers from 1 to 10.

Show code
player_id <- 1:10
print(player_id)

Vector operations

Create two vectors [var_a] and [var_b]. [var_a] should contain numbers from 1 to 5, and [var_b] contain numbers from 6 to 10. Then add, subtract, multiply, and divide these vectors.

Show code
a <- 1:5
b <- 6:10
print(a + b)
print(a - b)
print(a * b)
print(a / b)

Logical operators with vectors

Create a vector [total_goals] with the values 15, 23, 17, 21, 19. Use a logical operator to determine which values stored in the vector [total_goals] are greater than 18.

Show code
total_goals <- c(15, 23, 17, 21, 19)
print(total_goals > 18)

Vector indexing

With the vector [total_goals] from the previous exercise, use indexing to print the 2nd and 4th values in the vector [total_goals].

Show code
print(total_goals[c(2,4)])

Vector functions

Working with the vector [total_goals], find the minimum, maximum, sum, and mean of the [total_goals].

Print these values to the console window.

Show code
print(min(total_goals))
print(max(total_goals))
print(sum(total_goals))
print(mean(total_goals))

Named vectors

Create a named vector [players_signed] that contains the number of forwards, midfielders, defense, and goalkeepers. Set the values to 10, 8, 8, and 3, respectively.

Show code
players_signed <- c(forwards = 10, midfielders = 8, defense = 8, goalkeepers = 3)
print(players_signed)

Manipulating named vectors

Using the vector [players_signed] from the previous exercise, add 5 to the number of forwards, subtract 2 from the number of midfielders, and print the updated vector.

Show code
players_signed["forwards"] <- players_signed["forwards"] + 5
players_signed["midfielders"] <- players_signed["midfielders"] - 2

print(players_signed)